#include <stdlib.h>
#include "avr_compiler.h"
#include "uart.h"
#include <stdio.h>
#include "support.h"

void sendchar(USART_data_t * uart, uint8_t buffer){
	char bytetobuffer;
	do{
		bytetobuffer = USART_TXBuffer_PutByte(uart, buffer);
	}while(!bytetobuffer);

}
void sendstring(USART_data_t * uart, uint8_t *buffer){
	int i;
	for(i=0;buffer[i]!=0;i++){
		sendchar(uart, buffer[i]);
	}
}


void sprintBinary(uint8_t * buffer, int * value){
	int i;
	int k = 2;
	buffer[0] = '0';
	buffer[1] = 'b';
	for(i = 15; i >= 0; i --, k++){
		if(*value & (1 << i)){
			buffer[k] = '1';
		}
		else{
			buffer[k] = '0';
		}
	}
	sprintf((char*)&buffer[18], "\n\r");
}
	
/*USART Initiate*/
void uartInitiate(USART_data_t * title,USART_t * interface, unsigned long int baudrate){
	USART_InterruptDriver_Initialize(title, interface, USART_DREINTLVL_LO_gc);
	USART_Format_Set(title->usart, USART_CHSIZE_8BIT_gc, USART_PMODE_DISABLED_gc, false);
	USART_RxdInterruptLevel_Set(title->usart, USART_RXCINTLVL_LO_gc);

	if(CPU_SPEED == 32000000){

		if (baudrate == 4608){
			USART_Baudrate_Set(interface, 214, -6);
		}
		else if(baudrate == 1152){
			USART_Baudrate_Set(interface, 1047, -6);
		}
		else if(baudrate == 384){
			USART_Baudrate_Set(interface, 3269 , -6);
		}
		else if(baudrate == 584){
			USART_Baudrate_Set(interface, 2128, -6);
		}
		else if(baudrate == 576){
			USART_Baudrate_Set(interface, 2158, -6);
		}
		else if(baudrate == 96){
			USART_Baudrate_Set(interface, 3317 , -4);
		}
	}
	else if(CPU_SPEED == 12000000){

		if (baudrate == 4608){
			USART_Baudrate_Set(interface, 40, -6);

			//PORTA.OUT = 3;
		}
		else if(baudrate == 1152){
			USART_Baudrate_Set(interface, 353, -6);
		}
		else if(baudrate == 384){
			USART_Baudrate_Set(interface, 1186, -6);
		}
		else if(baudrate == 584){
			USART_Baudrate_Set(interface, 758, -6);
		}
		else if(baudrate == 576){
			USART_Baudrate_Set(interface, 769, -6);
		}
		else if(baudrate == 96){
			USART_Baudrate_Set(interface, 2468 , -5);
		}
	}


	USART_Rx_Enable(title->usart);
	USART_Tx_Enable(title->usart);
	
}

